using System;
using CodePlex.TfsLibrary.ClientEngine;
using CodePlex.TfsLibrary.ObjectModel;
using CodePlex.TfsLibrary.RepositoryWebSvc;

namespace CodePlex.CodePlexClientLibrary
{
    public class ListConsoleView : IListView
    {
        readonly ListViewPresenter presenter;
        string serverPath;
        bool verbose;

        public ListConsoleView(ITfsEngine engine)
        {
            presenter = new ListViewPresenter(this, engine);
        }

        public void DisplayItem(SourceItem item,
                                SourceItemResult result)
        {
            if (item.RemoteName.Length > serverPath.Length)
                if (verbose)
                    DisplayItem_Verbose(item);
                else
                    DisplayItem_Standard(item);
        }

        void DisplayItem_Standard(SourceItem item)
        {
            Console.WriteLine(RelativeName(item));
        }

        void DisplayItem_Verbose(SourceItem item)
        {
            Console.WriteLine("{0}   {1}   {2:yyyy-MM-dd HH:mm}   {3}   {4}",
                              item.RemoteChangesetId.ToString().PadLeft(8),
                              item.ItemId.ToString().PadLeft(8),
                              item.RemoteDate,
                              ItemSize(item),
                              RelativeName(item));
        }

        static string ItemSize(SourceItem item)
        {
            if (item.ItemType == ItemType.Folder)
                return "<DIR>".PadRight(13);
            else
                return item.RemoteSize.ToString("N0").PadLeft(13);
        }

        string RelativeName(SourceItem item)
        {
            string name = item.RemoteName.Substring(serverPath.Length);

            if (item.ItemType == ItemType.Folder)
                name += "/";

            return name;
        }

        public void Run(string tfsUrl,
                        string tfsServerPath,
                        bool recursive,
                        VersionSpec version,
                        bool verboseOutput)
        {
            serverPath = tfsServerPath;
            verbose = verboseOutput;

            if (!serverPath.EndsWith("/"))
                serverPath += "/";

            presenter.Run(tfsUrl, tfsServerPath, recursive, version);
        }
    }
}